// pages/food/food.js
var Api = require('../../utils/api.js');

Page({
  data: {
    hiddenAddForm: 1,
    foodId: 0,
    eatTypes: ['早餐', '午餐', '晚餐', '零食'],
    eatTypeIndex: 0,
    eatNums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    eatNumIndex: 0,
    time: '08:00',
    unitsCheckedIndex: 0,
    result: {
      id: 0,
      name: "未知食物",
      components: [
        { unit_name: "克", _id: 1 },
        { unit_name: "毫升", _id: 2 }
      ],
      href: "",
      type: 0
    },
  },

  TimeChange(e) {
    this.setData({
      time: e.detail.value
    });
  },

  eatTypeChange(e) {
    this.setData({
      eatTypeIndex: e.detail.value
    });
  },

  eatNumChange(e) {
    this.setData({
      eatNumIndex: e.detail.value
    });
  },

  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    });
  },

  hideModal(e) {
    this.setData({
      modalName: null
    });
  },

  unitsChange: function(e) {
    this.setData({
      unitsCheckedIndex: e.detail.value
    });
  },

  formSubmit: function(e) {
    console.log(e);
    // 添加食物或运动数据
    var params = {
      food_id: this.data.foodId,
      unit_name: this.data.result.components[this.data.unitsCheckedIndex].unit_name,
      unit_id: this.data.result.components[this.data.unitsCheckedIndex]._id,
      eat_type: parseInt(e.detail.value.eat_type),
      eat_time: this.data.time,
      eat_num: parseInt(e.detail.value.eat_num) + 1
    };
    
    // 如果是运动数据，添加 type: 1 标识
    if (this.data.result.type === 1) {
      params.type = 1;
    }
    console.log("params", params);

    wx.showLoading({
      title: '添加中',
    });

    wx.request({
      url: Api.eat(),
      data: params,
      method: "PUT",
      dataType: "json",
      success: function(res) {
        console.log(res.data);
        wx.showToast({
          title: '已完成',
          icon: 'success',
          duration: 4000,
          complete: function() {
            wx.switchTab({
              url: "/pages/index/index"
            });
          }
        });
      },
      fail: function() { // 模拟成功的响应
        console.log("请求失败，模拟成功添加数据");
        wx.showToast({
          title: '模拟添加成功',
          icon: 'success',
          duration: 2000
        });
        setTimeout(() => {
          wx.switchTab({
            url: "/pages/index/index"
          });
        }, 2000);
      }
    });
  },

  onShareAppMessage(o) {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 验证必需的 id 参数
    if (!options.id || options.id.trim() === '') {
      wx.showModal({
        title: '参数错误',
        content: '缺少食物ID参数，请从搜索页面选择食物',
        showCancel: false,
        success: function() {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      });
      return;
    }

    if (options.hidden_add_form) {
      this.setData({
        hiddenAddForm: 0,
      });
    }

    if (!options.eat_type) {
      options.eat_type = 0;
    } else {
      options.eat_type = parseInt(options.eat_type);
    }

    wx.showLoading({
      title: '加载中',
    });

    var eatTime = this.data.time;
    if (options.eat_type === 1) {
      eatTime = "12:00";
    } else if (options.eat_type === 2) {
      eatTime = "18:30";
    } else if (options.eat_type === 3) {
      eatTime = "15:00";
    }

    this.setData({
      foodId: options.id,
      eatTypeIndex: options.eat_type,
      time: eatTime
    });

    var that = this;
    wx.request({
      url: Api.foodInfo({ id: options.id }),
      success: function(res) {
        console.log(res.data);
        that.setData({
          result: res.data
        });
        wx.hideLoading();
      },
      fail: function() { // 如果请求失败，使用模拟的 foodInfo 数据
        console.log("请求失败，使用模拟数据");
        const mockData = {
          id: options.id || 0,
          name: "米饭",
          components: [
            { unit_name: "200克", _id: 1 },
            { unit_name: "毫升", _id: 2 }
          ],
          href: "https://lao-beijing.com/wp-content/uploads/2023/11/plain-rice.jpg",
          type: 1
        };
        that.setData({
          result: mockData
        });
        wx.hideLoading();
      }
    });
  }
});
